package com.tobeface.wechat.web;

import com.tobeface.modules.lang.IOs;
import com.tobeface.modules.lang.Langs;
import com.tobeface.wechat.message.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;

/**
 * @author loudyn
 */
final class WeChatHttpMessageContexts {

    /**
     * @param request
     * @param response
     * @return
     */
    static WeChatMessageContext ofMessageContext(HttpServletRequest request, HttpServletResponse response) {
        WeChatMessage message = buildMessage(request);
        WeChatMessageChannel channel = buildMessageChannel(response);
        WeChatMessageCredential credential = buildMessageCredential(request);
        return WeChatMessageContext.of(channel, credential, message);
    }

    private static WeChatMessage buildMessage(HttpServletRequest httpReq) {
        try {

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            IOs.piping(httpReq.getInputStream(), out);
            return WeChatMessageBuilder.loads(out.toByteArray()).verb(httpReq.getMethod()).build();
        } catch (Exception e) {
            throw Langs.toUncheck(e);
        }
    }

    private static WeChatMessageChannel buildMessageChannel(HttpServletResponse resp) {
        try {
            return new OutputStreamMessageChannel(resp.getOutputStream());
        } catch (Exception e) {
            throw Langs.toUncheck(e);
        }
    }

    private static WeChatMessageCredential buildMessageCredential(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        return WeChatMessageCredential.newBuilder().signature(signature).timestamp(timestamp)
                                                    .nonce(nonce).echostr(echostr)
                                                    .build();
    }

    private WeChatHttpMessageContexts() {
    }
}
